package com.oracle.zebrafreelytraveling.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;

import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResCard;
import com.oracle.zebrafreelytraveling.net.Api;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.HeaderAndFooterWrapper;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.LoadMoreWrapper;
import com.oracle.zebrafreelytraveling.ui.CardInfoActivity;
import com.oracle.zebrafreelytraveling.ui.adapter.CardsListAdapter;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/7/20.
 * 论坛fragment
 */

public class ForumFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private SwipeRefreshLayout mRefreshLayout;

    private RecyclerView mForumRecycleView;
    private CardsListAdapter mCardsListAdapter;
    private HeaderAndFooterWrapper mHFWrapper;
    private LoadMoreWrapper mLoadMoreWrapper;

    private List<ResCard.DataBean> mList;

    private View mView;
    private View mHeaderView;
    private Disposable mDisposable;

    private Spinner mForumClassifySort;
    private Spinner mForumNumSort;
    private TextView mTVNumSort;
    private TextView mTVClassifySort;

    private String currentCity;

    private ViewHolder holder;

    private int page = 0;
    private boolean isListNull = false;
    private int labelType = -1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_forum, container, false);
        mHeaderView = LayoutInflater.from(getContext()).inflate(R.layout.header_item_forum_sort, container, false);
        initView();
        mList = new ArrayList<>();
        mForumRecycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mCardsListAdapter = new CardsListAdapter(getActivity(), R.layout.item_cards, mList);
        mCardsListAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                CardInfoActivity.startCardInfoActivity(getActivity(), mList.get(position - 1));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                //TODO 分享...
                return false;
            }
        });
        mForumRecycleView.setItemAnimator(new DefaultItemAnimator());
        initHeaderAndFooter();
        mForumRecycleView.setAdapter(mHFWrapper);
        return mView;
    }

    private void initView() {
        mForumRecycleView = (android.support.v7.widget.RecyclerView) mView.findViewById(R.id.forum_recycleView);
        mRefreshLayout = (SwipeRefreshLayout) mView.findViewById(R.id.forum_refresh);
        mRefreshLayout.setColorSchemeColors(getResources().getColor(android.R.color.holo_blue_light));
        mRefreshLayout.setOnRefreshListener(this);
    }

    private void initHeaderAndFooter(){
        initHeader();
        mLoadMoreWrapper = new LoadMoreWrapper(mCardsListAdapter);
        mHFWrapper = new HeaderAndFooterWrapper(mLoadMoreWrapper);
        mHFWrapper.addHeaderView(mHeaderView);
        mLoadMoreWrapper.setLoadMoreView(R.layout.footer_loading);
        mLoadMoreWrapper.setOnLoadMoreListener((viewholder) -> {
            holder = viewholder;
            if (!isListNull){
                if (!TextUtils.isEmpty(currentCity)){
                    updateCardList(Constant.GET_DATA_TYPE_LOADMORE, Constant.RES_CITY);
                } else {
                    updateCardList(Constant.GET_DATA_TYPE_LOADMORE, Constant.RES_COUNTRY);
                }
            } else {
                viewholder.getConvertView().setVisibility(View.GONE);
            }

        });
    }

    private void initHeader(){
        mTVClassifySort = (TextView) mHeaderView.findViewById(R.id.tv_classify_sort);
        mTVNumSort = (TextView) mHeaderView.findViewById(R.id.tv_num_sort);
        mForumClassifySort = (Spinner) mHeaderView.findViewById(R.id.forum_classify_sort_btn);
        mForumNumSort = (Spinner) mHeaderView.findViewById(R.id.forum_num_sort_btn);
        mForumClassifySort.setSelection(getResources().getStringArray(R.array.classify_sort).length - 1);
        mForumNumSort.setSelection(getResources().getStringArray(R.array.num_sort).length - 1);
        mForumClassifySort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                forumClassifySort(position);
                labelType = position;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mForumNumSort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                forumNumSort(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    public void setCurrentCity(String city){
        currentCity = city;
        if (getUserVisibleHint()){
            updateCardList(Constant.GET_DATA_TYPE_NOMAL, Constant.RES_CITY);
        }
        Log.d("currentForum", city);
    }

    /**
     * 按分类筛选
     */
    private void forumClassifySort(int type){
        List<ResCard.DataBean> list = new ArrayList<>();
        Observable.just(mList).flatMap(Observable::fromIterable)
                .filter(dataBean -> dataBean.getCard().getLabel().contains(type + ""))
                .subscribe(list::add);
        if (list.size() != 0){
            mList.clear();
            mList.addAll(list);
            mCardsListAdapter.notifyDataSetChanged();
        } else {
            if (!TextUtils.isEmpty(currentCity)){
                updateCardList(Constant.GET_DATA_TYPE_NOMAL, Constant.RES_CITY);
            } else {
                updateCardList(Constant.GET_DATA_TYPE_NOMAL, Constant.RES_COUNTRY);
            }
        }

    }

    /**
     * 按数值排序
     */
    private void forumNumSort(int type){
        if (mList.size() <= 1){
            return;
        }
        if (type == Constant.SORT_RECEVE){
            Collections.sort(mList, (o1, o2) -> o2.getCard().getReceive() - o1.getCard().getReceive());
        } else if (type == Constant.SORT_TIME){
            Collections.sort(mList, (o1, o2) -> (int) (Double.parseDouble(o2.getCard().getTime()) - Double.parseDouble(o1.getCard().getTime())));
        }
        mCardsListAdapter.notifyDataSetChanged();
    }


    //TODO 函数属性 view 景点(需要添加的属性)
    public void updateCardList(int type, int resType) {
        Api api = HttpManager.getInstance().getService(Constant.BASE_URL);
        Observable<ResCard> observable = null;
        if (labelType != -1){
            if (resType == Constant.RES_CITY){
                observable = api.getCardsWithLabel(currentCity, labelType, page , Constant.MAX_PAGE);
            } else {
                observable = api.getCardsWithLabel("", labelType, page , Constant.MAX_PAGE);
            }
        } else {
            if (resType == Constant.RES_CITY){
                observable = api.getResCardsFromCity(currentCity, page, Constant.MAX_PAGE);
            } else {
                observable = api.getResCardsFromCountry(page, Constant.MAX_PAGE);
            }
        }
        if (observable == null){
            return;
        }
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResCard>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }
                    @Override
                    public void onNext(@NonNull ResCard value) {
                        if (value.getCode().equals(Constant.REQUEST_FAULT)) {
                            //服务端请求数据发生错误
                            ToastUtil.showToast(getString(R.string.not_any_more));
                            page = 0;
                            holder.getConvertView().setVisibility(View.GONE);
                            isListNull = true;
                            return;
                        }
                        //更新界面数据
                        if (Constant.GET_DATA_TYPE_NOMAL == type) {
                            //正常模式下，清空之前数据，重新加载
                            mList.clear();
                            mList.addAll(value.getData());
                            isListNull = false;
                        } else if (Constant.GET_DATA_TYPE_LOADMORE == type) {
                            //加载更多模式
                            mList.addAll(value.getData());
                        }
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        //加载界面停止
                        mRefreshLayout.setRefreshing(false);
                        holder.getConvertView().setVisibility(View.GONE);
                        ToastUtil.showToast(e.getMessage());
                        Log.d("mRefreshLayout", "false error" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //加载界面停止
                        mRefreshLayout.setRefreshing(false);
                        holder.getConvertView().setVisibility(View.GONE);
                        mHFWrapper.notifyDataSetChanged();
                    }
                });
        page++;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //清除 Disposable
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        page = 0;
    }

    @Override
    public void onRefresh() {
        //设置可见
        mRefreshLayout.setRefreshing(true);
        if (currentCity != null && currentCity.length() > 0){
            updateCardList(Constant.GET_DATA_TYPE_LOADMORE, Constant.RES_CITY);
        } else {
            updateCardList(Constant.GET_DATA_TYPE_LOADMORE, Constant.RES_COUNTRY);
        }
    }
}
